package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.SysKey;
import com.ruoyi.system.domain.SysKeyNz;
import com.ruoyi.system.domain.SysUserAccount;
import com.ruoyi.system.mapper.SysKeyMapper;
import com.ruoyi.system.mapper.SysKeyNzMapper;
import com.ruoyi.system.mapper.SysUserAccountMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.SysKeyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysKeyServiceImpl implements SysKeyService {
    @Resource
    private SysKeyMapper sysKeyMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserAccountMapper sysUserAccountMapper;
    @Resource
    private SysKeyNzMapper sysKeyNzMapper;


    /**
     * @param sysKey 卡密实体类
     * @Deprecated 查询自己的卡密
     */
    @Override
    public ArrayList<SysKey> getMyKeyTableDataInfo(SysKey sysKey) {
        sysKey.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        if (sysKey.getSelectName() != null && !sysKey.getSelectName().isEmpty()) {
            List<SysUser> sysUserList = new ArrayList<>();
            // 根据名称查询用户id
            SysUser sysUserQuery = sysUserMapper.selectUserByUserName(sysKey.getSelectName());
            if (sysUserQuery == null) {
                throw new RuntimeException("查询的用户不存在.");
            } else {
                // 查询这个代理及子代理
                List<SysUser> sysUsers = sysUserMapper.selectUserList(new SysUser());
                for (SysUser sysUser : sysUsers) {
                    if (sysUser.getFatherId().contains(String.valueOf(sysUserQuery.getUserId()))) {
                        // 查询上级用户名称
                        if (sysUser.getFatherId().contains(",")) {
                            String[] split = sysUser.getFatherId().split(",");
                            SysUser sysUser1 = sysUserMapper.selectUserById(Long.valueOf(split[0]));
                            sysUser.setFatherName(sysUser1.getUserName());
                        } else {
                            SysUser sysUser1 = sysUserMapper.selectUserById(Long.valueOf(sysUser.getFatherId()));
                            sysUser.setFatherName(sysUser1.getUserName());
                        }
                        sysUserList.add(sysUser);
                    }
                }
            }
            // 查询用户列表的所有卡密
            sysUserList.add(sysUserQuery);
            String[] ids = new String[sysUserList.size()];
            for (int i = 0; i < sysUserList.size(); i++) {
                ids[i] = String.valueOf(sysUserList.get(i).getUserId());
            }
            return sysKeyMapper.selectSysKeyListByUserId(ids);
        } else {
            return sysKeyMapper.selectSysKeyList(sysKey);
        }
    }

    /**
     * @param sysKey 卡密实体类
     * @Deprecated 新增自己的卡密
     */
    @Override
    public AjaxResult addKey(SysKey sysKey) {
        if (sysKey.getNumber() <= 0) {
            return AjaxResult.error("数量不能低于1张");
        }
        if (sysKey.getNumber() > 500) {
            return AjaxResult.error("单次数量不能大于500张");
        }
        StringBuilder stringBuffer = new StringBuilder();
        for (int i = 0; i < sysKey.getNumber(); i++) {
            sysKey.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
            sysKey.setIsActivated("0");
            sysKey.setAccount("未使用");
            sysKey.setPersonName(SecurityUtils.getUsername());
            sysKey.setStatus("0");
            String key = UUID.randomUUID().toString().replace("-", "");
            switch (sysKey.getKeyTypes()) {
                case "0":
                    sysKey.setKeyNumber("TK" + key);
                    break;
                case "1":
                    sysKey.setKeyNumber("ZK" + key);
                    break;
                case "2":
                    sysKey.setKeyNumber("YK" + key);
                    break;
                case "3":
                    sysKey.setKeyNumber("CS" + key);
                    break;
            }
            stringBuffer.append(sysKey.getKeyNumber()).append("\n");
            sysKeyMapper.insertSysKey(sysKey);
        }
        return AjaxResult.success("新增成功", stringBuffer.toString());
    }

    /**
     * @param sysKey 卡密实体类
     * @Deprecated 删除自己的卡密
     */
    @Override
    public AjaxResult delKey(SysKey sysKey) {
        sysKeyMapper.deleteSysKeyById(sysKey);
        return AjaxResult.success("删除成功");
    }


    /**
     * @param ids 卡密集合
     * @Deprecated 删除自己的多个卡密
     */
    @Override
    public AjaxResult delKeyList(Long[] ids) {
        sysKeyMapper.deleteSysKeyByIds(ids);
        return AjaxResult.success("删除成功");
    }

    /**
     * @Deprecated 封停卡密
     */
    @Override
    public AjaxResult shutDown(String key) {
        // 查询当前卡密状态
        SysKey sysKey = sysKeyMapper.selectSysKey(key);
        sysKey.setStatus(sysKey.getStatus().equals("1") ? "0" : "1");
        sysKeyMapper.shutDown(sysKey);
        return AjaxResult.success(sysKey.getStatus().equals("1") ? "封停成功" : "解封成功");
    }

    /**
     * @Deprecated 设置用户过期
     */
    @Override
    public AjaxResult gq(SysKey sysKey) {
        // 修改卡密到期时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            sysKey.setExpirationTime(sdf.parse("2001-08-08 08:08:08"));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        sysKeyMapper.updateKeyInfoById(sysKey);

        // 通过卡密id查询卡密用户
        SysKey queryOne = sysKeyMapper.selectSysKeyBindAccount(sysKey.getId());
        SysUserAccount sysUserAccount = new SysUserAccount();
        sysUserAccount.setAccount(queryOne.getAccount());
        sysUserAccount.setEndTime("2001-08-08 08:08:08");
        // 设置用户到期
        sysUserAccountMapper.updateSysUserAccountByAccount(sysUserAccount);
        return AjaxResult.success("设置用户到期成功");
    }

    @Override
    @Transactional
    public AjaxResult plda(String data) {
        /*String[] dataArray = data.split("\n");
        ArrayList<String> arrayList = new ArrayList<>();
        for (String s : dataArray) {
            // 通过key查询id
            SysKey sysKey = sysKeyMapper.selectSysKeyByKey(s);
            // 修改卡密到期时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                sysKey.setExpirationTime(sdf.parse("2001-08-08 08:08:08"));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            sysKeyMapper.updateKeyInfoById(sysKey);

            // 通过卡密id查询卡密用户
            SysKey queryOne = sysKeyMapper.selectSysKeyBindAccount(sysKey.getId());
            SysUserAccount sysUserAccount = new SysUserAccount();
            sysUserAccount.setAccount(queryOne.getAccount());
            sysUserAccount.setEndTime("2001-08-08 08:08:08");
            // 设置用户到期
            sysUserAccountMapper.updateSysUserAccountByAccount(sysUserAccount);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("未激活的卡是:" + arrayList.size());*/
        /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = "2024-09-26 04:01:13";
        SysKeyNz sysKeyNz = new SysKeyNz();
        try {
            sysKeyNz.setExpirationTime(sdf.parse(time));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        sysKeyNz.setKeyNumber("JTZK9CJUBNRZ228D498405A8424CAD5ED0A66CD7B139");
        sysKeyNz.setPersonName("13371680250");
        sysKeyNz.setIsActivated("1");
        sysKeyNz.setStatus("0");
        sysKeyNz.setDelFlag("0");
        sysKeyNz.setCreateBy("6");
        sysKeyNz.setKeyTypes("1");
        sysKeyNzMapper.insertSysKeyNz(sysKeyNz);*/
        return AjaxResult.success("批量设置用户到期成功");
    }
}
